package com.neusoft.elmboot.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.neusoft.elmboot.mapper.OrdersMapper;
import com.neusoft.elmboot.mapper.PointMapper;
import com.neusoft.elmboot.po.Orders;
import com.neusoft.elmboot.po.Point;
import com.neusoft.elmboot.po.PointRollover;
import com.neusoft.elmboot.service.PointService;

@Service
public class PointServiceImpl implements PointService{
	
	@Autowired
	private PointMapper pointmapper;
	
	@Autowired OrdersMapper ordersmapper;

	@Override
	public Object getPointByUserId(String userId) {
		return pointmapper.getSumLegalPointsListByUserId(userId);
	}

	@Override
	public int consumePoint(int orderId,String userId) {
		Orders order = ordersmapper.getOrdersById(orderId); 
		int consumedTotalPoint=order.getConsumedPoint();
		pointmapper.consumePoint(userId,consumedTotalPoint);
		List<Point> listpoints = pointmapper.getLegalPointsListByUserId(userId);
		for(Point point:listpoints) {
			int curPoint=Math.min(point.getPoint(), consumedTotalPoint);
			consumedTotalPoint-=curPoint;
			int leftPoint=point.getPoint()-curPoint;
			pointmapper.updatePointsByPointIdForConsume(leftPoint,point.getPointId());
			if(consumedTotalPoint==0) {
				break;
			}
		}
		return 0;
	}
	
	@Override
	@Transactional
	public int createPoint(int orderId,String userId) {
		Orders order = ordersmapper.getOrdersById(orderId); 
		int createdPoint = order.getOrderTotal().intValue();
		pointmapper.savePoint(userId, orderId, createdPoint);
		int pointId = pointmapper.getLastPointIdByUserId(userId);
		pointmapper.createPoint(userId,createdPoint);
		return createdPoint;
	}

	@Override
	public List<PointRollover> getCreatedPointsByUserId(String userId) {
		// TODO Auto-generated method stub
		return pointmapper.getCreatedPointListByUserId(userId);
	}

	@Override
	public List<PointRollover> getConsumedPointsByUserId(String userId) {
		// TODO Auto-generated method stub
		return pointmapper.getConsumedPointListByUserId(userId);
	}

	@Override
	public int consumePointByAmount(String userId, int amount) {
		int totalPoint = pointmapper.getSumLegalPointsListByUserId(userId);
		if(totalPoint<amount) {
			return -1;
		}
		pointmapper.consumePoint(userId,amount);
		List<Point> listpoints = pointmapper.getLegalPointsListByUserId(userId);
		for(Point point:listpoints) {
			int curPoint=Math.min(point.getPoint(), amount);
			amount-=curPoint;
			int leftPoint=point.getPoint()-curPoint;
			pointmapper.updatePointsByPointIdForConsume(leftPoint,point.getPointId());
			if(amount==0) {
				break;
			}
		}
		return 1;
	}

	@Override
	public List<PointRollover> getPointsByUserId(String userId) {
		// TODO Auto-generated method stub
		return pointmapper.getPointListByUserId(userId);
	}

}
